package com.hyd.springboot.controller;

import com.hyd.springboot.entity.Book;
import com.hyd.springboot.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    BookRepository bookRepository;

    //查询所有
    @GetMapping("/findAll/{page}/{size}")
    public Page<Book> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {

        Pageable pageable = PageRequest.of(page, size);  //设置分页，page查第一页默认从0开始，显示5行
        return bookRepository.findAll(pageable);
    }

    //添加数据
    @PostMapping("/save")
    public String save(@RequestBody Book book) {
        Book result = bookRepository.save(book);
        if (null != result) {
            return "success";
        } else {
            return "error";
        }
    }

    //查询单挑id的数据
    @GetMapping("/findById/{id}")
    public Book findById(@PathVariable("id") Integer id) {
        return bookRepository.findById(id).get();
    }

    //修改数据
    @PutMapping("/update")
    public String update(@RequestBody Book book){
        Book result = bookRepository.save(book);
        if (null != result) {
            return "success";
        } else {
            return "error";
        }
    }

    //删除
    @DeleteMapping("/deleteById/{id}")
    public void delete(@PathVariable("id") Integer id){
        bookRepository.deleteById(id);
    }
}
